package com.tyq.auth.security.service.impl;

import com.tyq.auth.security.service.MyAccessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义访问控制接口实现
 *
 * @author 谭永强
 * @date 2024-05-21
 */
@Service
public class MyAccessServiceImpl implements MyAccessService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 判断是否有权限访问
     *
     * @param request        请求
     * @param authentication 认证信息
     * @return true:有权限，false:无权限
     */
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if ("anonymousUser".equals(principal)) {
            logger.info("请求URI:{} - 未认证", request.getRequestURI());
            return false;
        }
        if (principal instanceof UserDetails) {
            //当前用户信息
            UserDetails userDetails = (UserDetails) principal;
            //根据当前用户信息查询API权限列表
            List<String> apiPermissionList = new ArrayList<>();
            apiPermissionList.add("/getCurrentUser");
            apiPermissionList.add("/hasPermission");
            for (String uri : apiPermissionList) {
                if (antPathMatcher.match(uri, request.getRequestURI())) {
                    logger.info("请求URI:{} - 访问权限:true", request.getRequestURI());
                    return true;
                }
            }
        }
        logger.info("请求URI:{} - 访问权限:false", request.getRequestURI());
        return false;
    }
}
